﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XDL.Framework;
using Microsoft.Xna.Framework;

namespace JumpNFight.Simulation
{
    class SpawnPattern
    {
       Timer m_timer;
       Timer m_waitTimer;
       bool[] m_pattern;
       int m_currentIndex = 0;

        public enum Direction
        {
            Left = 0,
            Right
        };

       public bool IsActive
       {
           get;
           private set;
       }

        /// <summary>
        /// Creates a new spawn pattern
        /// </summary>
        /// <param name="pause">Pause delay before starting the the pattern</param>
       /// <param name="interval">Interval between spawn events</param>
       /// <param name="pattern">Pattern</param>
       public SpawnPattern(TimeSpan pause, TimeSpan interval, string pattern)
       {
           m_timer = new Timer(interval);
           m_waitTimer = new Timer(pause);
           m_waitTimer.Start();
           IsActive = false;

           m_pattern = new bool[pattern.Length];
           int i = 0;
           foreach (char c in pattern)
           {
               m_pattern[i++] = (c == 'R');
           }
       }

       public void Start()
       {
           IsActive = true;
           Spawn = false;
           m_waitTimer.Reset();
           m_timer.Stop();
           m_currentIndex = -1;
       }

       public Direction SpawnDirection
       {
           get
           {
               if (!IsActive)
                   throw new InvalidOperationException("This spawn pattern is currently inactive");
               return m_pattern[m_currentIndex]?Direction.Right:Direction.Left;
           }
       }

       public bool Spawn
       {
           get;
           private set;
       }

       public void Update(GameTime gameTime)
       {
           Spawn = false;
           m_waitTimer.Update(gameTime);
           if (m_waitTimer.IsSignaled)
               m_timer.Start();

           m_timer.Update(gameTime);
           if (m_timer.IsSignaled)
           {
               m_currentIndex++;
               Spawn = true;
               if (m_currentIndex >= m_pattern.Length)
                   IsActive = false;
               // start over
               m_timer.Reset();
           }
       }
    }
}
